package com.pigcloud.sop.gateway.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pigcloud.sop.gateway.entity.ConfigLimit;
import com.pigcloud.sop.gateway.mapper.ConfigLimitMapper;
import com.pigcloud.sop.gatewaycommon.bean.ChannelMsg;
import com.pigcloud.sop.gatewaycommon.bean.ConfigLimitDto;
import com.pigcloud.sop.gatewaycommon.manager.DefaultLimitConfigManager;
import com.pigcloud.sop.gatewaycommon.util.MyBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 限流配置管理
 * @author wangfm
 */
@Slf4j
@Service
public class DbLimitConfigManager extends DefaultLimitConfigManager {

    @Autowired
    ConfigLimitMapper configLimitMapper;

    @Override
    public void load(String serviceId) {
        LambdaQueryWrapper<ConfigLimit> queryWrapper = Wrappers.lambdaQuery(ConfigLimit.class)
                        .eq(StringUtils.isNotBlank(serviceId), ConfigLimit::getServiceId, serviceId);
        configLimitMapper.selectList(queryWrapper)
                .forEach(this::putVal);
    }

    protected void putVal(ConfigLimit object) {
        ConfigLimitDto configLimitDto = new ConfigLimitDto();
        MyBeanUtil.copyPropertiesIgnoreNull(object, configLimitDto);
        this.update(configLimitDto);
    }

    @Override
    public void process(ChannelMsg channelMsg) {
        final ConfigLimitDto configLimitDto = channelMsg.toObject(ConfigLimitDto.class);
        switch (channelMsg.getOperation()) {
            case "reload":
                log.info("重新加载限流配置信息，configLimitDto:{}", configLimitDto);
                load(configLimitDto.getServiceId());
                break;
            case "update":
                log.info("更新限流配置信息，configLimitDto:{}", configLimitDto);
                update(configLimitDto);
                break;
            default:
        }
    }


}
